package com.keter.framework.web.util;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;

/**
 *  集合操作工具
 */
public class CollectionUtil {

    /**
     * 从包含ID属性的JSONArray中提取逗号分隔的ID串
     * ex：{"id":1,"id":2} -> "1,2"
     * @param array 包含id属性的JSONArray
     * @return
     */
    public  static String extactIDsFromArray(JSONArray array){
        return extactIDsFromArray(array,"id");
    }

    /**
     *  从JSONArray中提取逗号分隔的ID串
     *  ex：{"id":1,"id":2} -> "1,2"
     * @param array
     * @param attr  自定义属性名称
     * @return
     */
    public  static String extactIDsFromArray(JSONArray array, String attr){
        String idStr = "";
        for (int i = 0; i < array.size(); i++) {
            idStr = idStr.concat(array.getJSONObject(i).getString(attr)).concat(",");
        }
        return StringUtils.substringBeforeLast(idStr,",");
    }
}
